import sys
import requests
import json
from skimage import io
import tkinter
from tkinter import messagebox
import matplotlib.pyplot as plt
import os
import win32gui,win32con
from PIL import Image
from threading import Thread
import easygui
import time
import win32com.client as client
import ctypes #这个库将会用到
from shutil import move
import webbrowser as web
import winreg

# -*- coding: utf-8 -*-
# coding=utf-8

# Form implementation generated from reading ui file '托盘程序设置UI.ui'
#
# Created by: PyQt5 UI code generator 5.15.7
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QPixmap
from urllib.parse import quote

#from PyQt5.QtCore import QTextCodec

# 设置默认编码为UTF-8
#QTextCodec.setCodecForLocale(QTextCodec.codecForName("ANSII"))

import sys, os

user_setting = []
script_path = sys.argv[0]
script_directory = os.path.dirname(script_path)
root_path = script_directory + os.sep

import wx.adv

# 创建托盘图标的类

# 创建应用程序对象
# app = wx.App(False)

# # 创建任务栏图标对象
# task_bar_icon = MyTaskBarIcon()

# # 运行应用程序
# app.MainLoop()

def ifAdmin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False
    
def add_to_startup():
    key = winreg.HKEY_LOCAL_MACHINE
    key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
    value_name = "WallpaperGenerator"
    script_path = os.path.realpath(sys.argv[0])
    value_data = sys.executable + ' "' + script_path + '"'
    
    try:
        with winreg.OpenKey(key, key_path, 0, winreg.KEY_ALL_ACCESS|winreg.KEY_WRITE|winreg.KEY_CREATE_SUB_KEY) as reg_key:
            winreg.SetValueEx(reg_key, value_name, 0, winreg.REG_SZ, value_data)
            return True
    except:
        print('False')
        return False

def is_added_to_startup():
    key = winreg.HKEY_LOCAL_MACHINE
    key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
    value_name = "WallpaperGenerator"
    
    try:
        with winreg.OpenKey(key, key_path, 0, winreg.KEY_ALL_ACCESS|winreg.KEY_WRITE|winreg.KEY_CREATE_SUB_KEY) as reg_key:
            value = winreg.QueryValueEx(reg_key, value_name)
            script_path = os.path.abspath(sys.argv[0])
            if value[0] == sys.executable + ' "' + script_path + '"':
                return True
            else:
                return False
    except FileNotFoundError:
        return False
    
def remove_from_startup():
    key = winreg.HKEY_LOCAL_MACHINE
    key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
    value_name = "WallpaperGenerator"
    
    try:
        with winreg.OpenKey(key, key_path, 0, winreg.KEY_ALL_ACCESS|winreg.KEY_WRITE|winreg.KEY_CREATE_SUB_KEY) as reg_key:
            winreg.DeleteValue(reg_key, value_name)
            return True
    except FileNotFoundError as re:
        return False

root = tkinter.Tk()
root.withdraw()
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(398, 779)
        #Shet = '"#centralwidget{image: url(' + root_path + 'Bg.jpg);}"'
        Shet = os.path.join(script_directory, 'Bg.jpg')#root_path + 'Bg.jpg'
        #Shet = Shet.encode("gbk").decode("utf-8")
        # Shet = Shet.encode("utf-8").decode("latin1") 
        #url = QUrl.fromLocalFile(Shet)
        
    # 创建QPixmap对象，并设置为背景图片
        #pixmap = QPixmap(url.toLocalFile())
        print(Shet)
        print(type(Shet))
        MainWindow.setStyleSheet("#centralwidget{image: url(Bg.jpg);}") #f"#centralwidget{{background-image: url('{Shet}');}}" 
        MainWindow.setWindowFlag(QtCore.Qt.WindowCloseButtonHint, False)
        MainWindow.setFixedSize(MainWindow.width(), MainWindow.height());
        MainWindow.setWindowIcon(QtGui.QIcon(root_path + "ico.ico"))
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.checkBox = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox.setGeometry(QtCore.QRect(20, 270, 191, 19))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.checkBox.setFont(font)
        self.checkBox.setStyleSheet("")
        self.checkBox.setObjectName("checkBox")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(10, 70, 381, 101))
        font = QtGui.QFont()
        font.setFamily("钉钉进步体")
        font.setPointSize(9)
        font.setBold(True)
        font.setItalic(False)
        font.setWeight(75)
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)
        self.label.setFont(font)
        self.label.setStyleSheet("background-color: rgba(255, 255, 255, 128);")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(10, 260, 381, 391))
        font = QtGui.QFont()
        font.setFamily("钉钉进步体")
        font.setPointSize(9)
        font.setBold(True)
        font.setItalic(False)
        font.setWeight(75)
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("background-color: rgba(255, 255, 255, 128);")
        self.label_2.setObjectName("label_2")
        self.checkBox_2 = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox_2.setGeometry(QtCore.QRect(20, 300, 191, 19))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.checkBox_2.setFont(font)
        self.checkBox_2.setStyleSheet("")
        self.checkBox_2.setObjectName("checkBox_2")
        self.radioButton_3 = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton_3.setGeometry(QtCore.QRect(20, 390, 191, 19))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.radioButton_3.setFont(font)
        self.radioButton_3.setStyleSheet("")
        self.radioButton_3.setObjectName("radioButton_3")
        self.radioButton_4 = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton_4.setGeometry(QtCore.QRect(20, 420, 321, 19))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.radioButton_4.setFont(font)
        self.radioButton_4.setStyleSheet("")
        self.radioButton_4.setObjectName("radioButton_4")
        self.radioButton_5 = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton_5.setGeometry(QtCore.QRect(20, 450, 361, 19))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.radioButton_5.setFont(font)
        self.radioButton_5.setStyleSheet("")
        self.radioButton_5.setObjectName("radioButton_5")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(260, 730, 121, 28))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(130, 730, 121, 28))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(10, 730, 71, 28))
        self.pushButton_3.setObjectName("pushButton_3")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(20, 350, 141, 31))
        font = QtGui.QFont()
        font.setFamily("钉钉进步体")
        font.setPointSize(9)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(50)
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)
        self.label_3.setFont(font)
        self.label_3.setStyleSheet("")
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(20, 610, 221, 31))
        font = QtGui.QFont()
        font.setFamily("钉钉进步体")
        font.setPointSize(9)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(50)
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)
        self.label_4.setFont(font)
        self.label_4.setStyleSheet("")
        self.label_4.setObjectName("label_4")
        self.radioButton_6 = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButton_6.setGeometry(QtCore.QRect(20, 480, 361, 19))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.radioButton_6.setFont(font)
        self.radioButton_6.setStyleSheet("")
        self.radioButton_6.setObjectName("radioButton_6")
        self.label_2.raise_()
        self.checkBox.raise_()
        self.label.raise_()
        self.checkBox_2.raise_()
        self.radioButton_3.raise_()
        self.radioButton_4.raise_()
        self.radioButton_5.raise_()
        self.radioButton_6.raise_()
        self.pushButton.raise_()
        self.pushButton.clicked.connect(main_function.save)
        self.pushButton_2.raise_()
        self.pushButton_2.clicked.connect(main_function.not_save)
        self.pushButton_3.raise_()
        self.pushButton_3.clicked.connect(main_function.about)
        self.label_3.raise_()
        self.label_4.raise_()
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "托盘程序设置"))
        self.checkBox.setText(_translate("MainWindow", "开机自启动"))
        self.label.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:20pt; font-weight:600; color:#000000;\">壁纸生成器</span></p><p align=\"center\"><span style=\" font-size:20pt; font-weight:600; color:#000000;\">自动壁纸 - 托盘程序设置</span></p></body></html>"))
        self.label_2.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><br/></p></body></html>"))
        self.checkBox_2.setText(_translate("MainWindow", "启动后自动更换壁纸"))
        self.radioButton_3.setText(_translate("MainWindow", "电脑壁纸"))
        self.radioButton_4.setText(_translate("MainWindow", "星空壁纸（可能包含不合适的尺寸）"))
        self.radioButton_5.setText(_translate("MainWindow", "随机壁纸（可能包含不合适的尺寸）"))
        self.pushButton.setText(_translate("MainWindow", "保存并退出"))
        self.pushButton_2.setText(_translate("MainWindow", "不保存并退出"))
        self.pushButton_3.setText(_translate("MainWindow", "关于"))
        self.label_3.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:12pt; color:#000000;\">刷新的壁纸类型</span></p></body></html>"))
        self.label_4.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:12pt;\">更多功能敬请期待……</span></p></body></html>"))
        self.radioButton_6.setText(_translate("MainWindow", "AI 推荐（新）"))
        self.radioButton_6.setStyleSheet("color: red")

class main_function(Ui_MainWindow):


    def about():
        messagebox.showinfo('关于','名称：壁纸生成器 3.0 图片生成插件 - 托盘自动壁纸程序\n依赖API：MirlKoiAPI\n        API源：https://api.iw233.cn/api.php?\n        打包：思锐工作室\n\n')

    def MakeLink2(path, target, args='', icon=',0'):
        shell = client.Dispatch('Wscript.Shell')
        link = shell.CreateShortCut(path)
        link.TargetPath = target
        link.Arguments = args
        link.IconLocation = icon
        link.save()
        print(dir(link))

    def save():
        if os.path.isfile(root_path + "limit.ini") == True and (ui.radioButton_3.isChecked() == True or ui.radioButton_5.isChecked() == True): #在 3.0.0 正式版中加入此功能
            messagebox.showwarning("限制级","您所选择的选项包含可能会生成限制级壁纸的类型，由于限制配置，请您取消勾选“电脑壁纸”或“随即壁纸”选项。")
        else:
            global user_setting
            configs = []
            config = open(root_path + "RefreshSetting.Sr", "w")

            # 写入自启动事件的壁纸
            if ui.checkBox.isChecked() == True:
                
                filename_with_extension = os.path.basename(__file__)
                filename_without_extension = os.path.splitext(filename_with_extension)[0]

                ProgramPath = root_path + filename_without_extension + '.exe'
                print(ProgramPath)
                # if ctypes.windll.shell32.IsUserAnAdmin() == False: #检查是否是管理员权限
                #     ctypes.windll.shell32.ShellExecuteW(None,"runas", sys.executable, __file__, None, 1) #尝试自主提升权限
                # 这部分代码对下面的代码目前没有作用

                rst = add_to_startup()
                print(rst)
                if rst == True:
                    configs.append('AutoStart')
                else:
                    if is_added_to_startup() == False:
                        messagebox.showerror('意外的错误',"启动项无法添加，因为权限不足，因此该条目失效。请尝试以管理员身份重新运行此程序以解决问题。")
                    else:
                        print('1. ' + str(is_added_to_startup))
                        configs.append('AutoStart')
                # try:
                #     # main_function.MakeLink2('AutoWpChange.lnk', ProgramPath, '', ProgramPath)
                    
                #     # move('AutoWpChange.lnk', 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup')
                #     add_to_startup()
                #     configs.append('AutoStart')
                # except Exception as e:
                    # if os.path.isfile("C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\AutoWpChange.lnk") == False:
                    #     messagebox.showerror('意外的错误',"启动项无法添加，因为权限不足，因此该条目失效。请尝试以管理员身份重新运行此程序以解决问题。详细信息：\n\n" + str(e))
                    # else:
                    #     configs.append('AutoStart')
  
            else:
                # if os.path.isfile("C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\AutoWpChange.lnk") == True:
                #     try:
                #         os.remove("C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\AutoWpChange.lnk")
                #     except Exception as re:
                #         messagebox.showerror('意外的错误',"启动项无法删除，因为权限不足，因此该条目失效。请尝试以管理员身份重新运行此程序以解决问题。详细信息：\n\n" + str(re))
                #         configs.append('AutoStart')
                if is_added_to_startup() == True:
                    rst = remove_from_startup()
                    if rst:
                        pass
                    else:
                        messagebox.showerror('意外的错误',"启动项无法删除，因为权限不足，因此该条目失效。请尝试以管理员身份重新运行此程序以解决问题。")
                        configs.append('AutoStart')


            if ui.checkBox_2.isChecked() == True:
                configs.append('AutoChange')

            #判断生成类型是否遭受限制

            # 写入壁纸生成类型的配置
            if ui.radioButton_3.isChecked() == True:
                configs.append('PC')
            elif ui.radioButton_4.isChecked() == True:
                configs.append('Starry')
            else:
                configs.append('Ran')

            print(configs)
            config.write(str(configs))
            config.close()
            user_setting = configs
            MainWindow.hide()

            filename_with_extension = os.path.basename(__file__)
            filename_without_extension = os.path.splitext(filename_with_extension)[0]

            ProgramPath = root_path + filename_without_extension + '.exe'
            print(ProgramPath)

            messagebox.showinfo('已设置','配置已保存至本地，并将会立即生效')
        

    def not_save():
        MainWindow.hide()
        
    



# class icon_set(QObject):
#     show_main_window_signal = pyqtSignal()
#     def __init__(self, MainWindow, ui, open_window):

#         app = wx.App(False)

# # 创建任务栏图标对象
#         task_bar_icon = MyTaskBarIcon()

#         self.ui = ui
#         self.main_window = MainWindow

#         # menu = (
#         # pystray.MenuItem("菜单项 1", lambda: print("菜单项 1 被点击")),
#         # pystray.MenuItem("菜单项 2", lambda: self.main_window.show()))

#         # tray_menu = pystray.Menu(*menu)

#         self.show_main_window_signal.connect(self.main_window.show)
#         # 运行应用程序
#         app.MainLoop()
        # self.thr1 = Thread(target=self.showing_window)
        # menu = (MenuItem('生成并刷新壁纸',action=self.handrefresh), MenuItem('打开设置', self.settings), MenuItem('退出', action=self.end))
        # image = Image.open("ico.ico")
        # self.icon = pystray.Icon("minmenu", image, "AI画图 - 每日自动刷新壁纸", menu=tray_menu)
        # self.thr1.start()
        # self.icon.run()
        
        # self.app = QtWidgets.QApplication(sys.argv)
        # self.MainWindow = QtWidgets.QMainWindow()
        # self.ui = Ui_MainWindow()
        # self.ui.setupUi(MainWindow)

def settings():
    global user_setting, ui, MainWindow
    # ui = Ui_MainWindow()
    # ui.setupUi(MainWindow)
    # 重置状态
    ui.checkBox.setChecked(False) 
    ui.checkBox_2.setChecked(False) 
    ui.radioButton_3.setChecked(False)
    ui.radioButton_4.setChecked(False)
    ui.radioButton_5.setChecked(False)
    
    if os.path.isfile(root_path + "RefreshSetting.Sr") == False:
        ui.checkBox.setChecked(True)
        ui.checkBox_2.setChecked(True)
        ui.radioButton_3.setChecked(True)
    else:
        user_config = open(root_path + "RefreshSetting.Sr", "r")
        user_setting = user_config.readline()
        user_config.close()

        # 根据配置修改状态
        if 'AutoStart' in user_setting:
            ui.checkBox.setChecked(True) 
        if 'AutoChange' in user_setting:
            ui.checkBox_2.setChecked(True) 

        if 'PC' in user_setting:
            ui.radioButton_3.setChecked(True)
        elif 'Starry' in user_setting:
            ui.radioButton_4.setChecked(True)
        else:
            ui.radioButton_5.setChecked(True)
    #app = QtWidgets.QApplication(sys.argv)
    #MainWindow1 = QtWidgets.QMainWindow()
    #ui1 = Ui_MainWindow()
    #ui1.setupUi(MainWindow1)
    #self.icon.stop()
    #self.MainWindow.show()
    MainWindow.show()
    #self.main_window.show()
    
    #MainWindow.setFocus()
    #print(MainWindow.hasFocus())
    #timer = QtCore.QTimer()
    #timer.singleShot(0, lambda: MainWindow.activateWindow())
    #print(MainWindow.isActiveWindow())
    #self.app.exec_()
    #icon.run()
    #MainWindow1.setFocus()
    #app1.exec_()
    
def notify():
    notification = wx.adv.NotificationMessage(
        title="AI画图 - 新壁纸",
        message="壁纸刷新成功",
        parent=None,
        flags=wx.ICON_INFORMATION
    )
    # self.icon.notify("壁纸刷新成功", "AI画图 - 新壁纸")
    notification.Show()

def error():
    notification = wx.adv.NotificationMessage(
        title="AI画图 - 未能刷新壁纸",
        message="壁纸刷新失败，错误报告已生成",
        parent=None,
        flags=wx.ICON_INFORMATION
    )
    notification.Show()
    # global icon
    # self.icon.notify("壁纸刷新失败，请多次重试", "AI画图 - 未能刷新壁纸")

def handrefresh():
    notification = wx.adv.NotificationMessage(
        title="开始",
        message="请等待，壁纸即将刷新",
        parent=None,
        flags=wx.ICON_INFORMATION
    )
    notification.Show()
    # global icon
    # self.icon.notify("请等待，壁纸即将刷新", "开始")
    refresh()


def end():
    os._exit(0)

#def tray_process_func():
def refresh():
    
    if 'PC' in user_setting:
        api = "https://api.iw233.cn/api.php?sort=pc"
    elif 'Starry' in user_setting:
        api = "https://api.iw233.cn/api.php?sort=xing"
    else:
        api = "https://api.iw233.cn/api.php?sort=random"

    parameters = {
        "type": "json",
        'num': 1
    }
    try:
        response = requests.get(api, params=parameters)
        # print(response.text())
        outputurl = json.dumps(response.json())
        print(outputurl)
        output = outputurl[10:-3]

        image = io.imread(output)
        io.imsave(root_path + 'wallpaper.bmp', image)
        img = plt.imread(root_path + 'wallpaper.bmp')
        path = os.path.abspath(root_path + 'wallpaper.bmp')
        win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,path, win32con.SPIF_SENDWININICHANGE)
        print(path)
        notify()
    except:
        time.sleep(1)
        error()
        easygui.exceptionbox()

class MyTaskBarIcon(wx.adv.TaskBarIcon):
    def __init__(self):
        super().__init__()
        self.SetIcon(wx.Icon(root_path + 'ico.ico'), '壁纸生成器 - 托盘程序')
        self.Bind(wx.adv.EVT_TASKBAR_LEFT_DCLICK, self.on_left_click)
        # self.tray_app = icon_set(MainWindow, ui, open_window)

    def CreatePopupMenu(self):
        # 创建弹出菜单
        menu = wx.Menu()
        menu.Append(1, '立刻生成并刷新壁纸')
        menu.Append(2, '打开生成设置')
        menu.AppendSeparator()
        menu.Append(3, '退出(若设定了开机启动，下次开机仍会启动)')
        menu.AppendSeparator()
        menu.Append(4, '捐赠几行代码，助力我们高效开发')
        self.Bind(wx.EVT_MENU, self.on_menu_1_select, id=1)
        self.Bind(wx.EVT_MENU, self.on_menu_2_select, id=2)
        self.Bind(wx.EVT_MENU, self.on_menu_3_select, id=3)
        self.Bind(wx.EVT_MENU, self.juanzeng, id=4)
        return menu

    def on_left_click(self, event):
        settings()
        

    def on_menu_1_select(self, event):
        handrefresh()
        

    def on_menu_2_select(self, event):
        settings()

    def on_menu_3_select(self, event):
        end()

    def juanzeng(self, event):
        web.open('https://afdian.net/a/srinternet')


if __name__ == '__main__':

    #tray_process = Process(target=tray_process_func)
    #tray_process.start()

    # level = ifAdmin()
    # print(level)
    # if level == False:
    #     os.environ['PYTHONIOENCODING'] = 'utf-8'
    #     params = [sys.executable] + sys.argv
    #     subprocess.run(params, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=subprocess.CREATE_NEW_CONSOLE)
    #     #r = ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
    #     # print(r)
    # level = ifAdmin()
    # print(level)
    # while r <= 32:
    #     if level == False:
    #         print("level")
    #         user_click = messagebox.askyesno('壁纸生成器 - 托盘程序', '在访问存储配置时遭到了系统的拒绝，因为程序不在管理员权限配置中运行。', 
    #                             icon=messagebox.ERROR, 
    #                             detail=" 单击“是(Y)”以重新以管理员身份运行此程序以解决问题。 ",
    #                             default=messagebox.YES)
    #         if user_click:
    #             r = ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
    #         else:
    #             os._exit(0)
    #     else:
    #         break

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    thr = Thread(target=refresh)
    
    open_window = False
    
    if os.path.isfile(root_path + "RefreshSetting.Sr") == False:
        ui.checkBox.setChecked(True)
        ui.checkBox_2.setChecked(True)
        ui.radioButton_3.setChecked(True)
        MainWindow.show()
    else:
        user_config = open(root_path + "RefreshSetting.Sr", "r")
        user_setting = user_config.readline()
        user_config.close()
        if 'AutoChange' in user_setting:
            thr.start()

    # thr1.start()
    #tray_app = icon_set(MainWindow, ui, open_window)
    app1 = wx.App(False)

# 创建任务栏图标对象
    task_bar_icon = MyTaskBarIcon()

    # self.ui = ui
    # self.main_window = MainWindow

    # # menu = (
    # # pystray.MenuItem("菜单项 1", lambda: print("菜单项 1 被点击")),
    # # pystray.MenuItem("菜单项 2", lambda: self.main_window.show()))

    # # tray_menu = pystray.Menu(*menu)

    # self.show_main_window_signal.connect(self.main_window.show)
    # 运行应用程序
    app1.MainLoop()
    # showing_window()
    
    #thr1 = settings()

    #MainWindow.show()
    # Main = icon_set()
    #tray_process.join()






